import socket
import threading
import os
import select


##服务端


def tcpserve():
    global clients
    global inputs
    global outputs

##    if not os.path.exists('d:/chat/'):
##        os.makedirs('d:/chat/')
    

    while True:
        stdinput, stdoutput, stderr = select.select(inputs, outputs, inputs)
        for obj in stdinput:
            if obj is s:
                c,addr=s.accept()
                inputs.append(c)
                clients[addr]=c
                for l in clients:
                    try:
                        clients[l].sendall('{}已登入'.format(str(addr)).encode('utf-8'))
                        print('{}已登入'.format(str(addr)))
                    except:
                        pass

            else:
                
                try:
                    acceptmsg=str(obj.recv(1024),encoding='utf-8')
         
                    print(''.join([acceptmsg,' 客户端口：',str(addr[1])]))
                    
                    accptdata=''.join([acceptmsg,' 客户端口：',str(addr[1])])
                    accptdata=accptdata+'\n'
                    for k in clients:
                        clients[k].sendall(accptdata.encode('utf-8'))
                    
                    if obj not in outputs:  
                            outputs.append(obj)
                except ConnectionResetError:
                    adr=obj.getpeername()
                    clients={k:v for k,v in clients.items() if k!=adr }
                    for b in clients:
                        try:
                            clients[b].sendall('{}已退出'.format(str(adr)).encode('utf-8'))
                            print('{}已退出'.format(str(adr)))
                        except:
                            print('err')
                    if not clients:
                        print('最后一位{}已退出'.format(str(adr)))
                    inputs.remove(obj)
                        

##        with open('d:/chat/c.txt','r') as f:
##            accptall=f.read()
##            sendmsg=accptall
##        c.sendall(sendmsg.encode('utf-8'))
##    c.close()

clients={}
outputs=[]
s=None

def main():
    global s
    global inputs
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    host='127.0.0.1'
    port=8800
    ##s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1024)
    s.bind((host,port))
    s.listen(5)
    inputs = [s]
    tcpserve()


if __name__=='__main__':
    main()


        

